import frappe
from frappe.query_builder.functions import Sum,IfNull
from pypika import  functions as fn

@frappe.whitelist()
def get_currency_precision():
    currency_precision=0
    currency_precision_temp=frappe.db.get_single_value('System Settings','currency_precision')
    if currency_precision_temp:
        currency_precision=int(currency_precision_temp)
    else:
        number_format=frappe.db.get_single_value('System Settings','number_format')
        if number_format.endswith('.##') or number_format.endswith(',##'):
            currency_precision=2 
        else:
            currency_precision=3
    return {'data':currency_precision}

@frappe.whitelist()
def get_fg_item_price(fg_item,supplier,buying_price_list,transaction_date):
    # 获取委外加工成品对应的加工费编码
    service_item_code = frappe.db.get_value('Item',fg_item,'custom_service_item')
    service_item_info = frappe.db.get_value('Item',service_item_code,['item_code', 'item_name','description','stock_uom'])
    item_code = service_item_info[0]
    item_name = service_item_info[1]
    description = service_item_info[2]
    uom = service_item_info[3]
    # 获取委外加工对应成品的价格
    item_price = frappe.qb.DocType('Item Price')
    #取fg_item的采购价
    q = frappe.qb.from_(item_price
        ).select(item_price.price_list_rate
        ).where(item_price.item_code == fg_item
        ).where((item_price.supplier == supplier) | (item_price.supplier.isnull()) | (item_price.supplier == '')
        ).where(item_price.buying == 1
        ).where(item_price.price_list == buying_price_list
        ).where((item_price.valid_from <= transaction_date) | (item_price.valid_from.isnull()) | (item_price.valid_from == '')
        ).where((item_price.valid_upto >= transaction_date) | (item_price.valid_upto.isnull()) | (item_price.valid_upto == '')
         ).orderby(item_price.valid_from, order=frappe.qb.desc
        ).orderby(IfNull(item_price.valid_upto, "2500-12-31"), order=frappe.qb.asc
        ).limit(1
        ).run(as_dict=1)
    if q:
        return {'data':{'rate':q[0].get('price_list_rate'),'item_code':item_code,'item_name':item_name,'description':description,'uom':uom}} 



@frappe.whitelist()
def test_custom_get_api():
    pass
    return {'data':'test_cust_api'}


"""
POST http://192.168.3.200:8083/api/method/zy_base.utils.test_custom_post_api HTTP/1.1
content-type: application/json
Authorization: token 211c17f2e8ff8be:51ac6427d48b9f5

{
    "frist_name": "zhangjinyang",
    "email": "zhangjinyang1@126.com",
    "password":"Admin_123456"
   
}

"""

# 外部可以调用这个API创建用户

@frappe.whitelist()
def test_custom_post_api():
    from frappe.core.doctype.user.user import test_password_strength
    from frappe.utils.password import update_password
    first_name=frappe.form_dict.get('frist_name')
    print(first_name)
    email=frappe.form_dict.get('email')
    print(email)
    new_password=frappe.form_dict.get('password')
    # 先判断用户是否存在
    if not frappe.db.get_value("User", email,'name'):
        # 检查密码是否可用
        result = test_password_strength(new_password)
        feedback = result.get("feedback", None)
        if feedback and not feedback.get("password_policy_validation_passed", False):
            if "feedback" in feedback:
                feedback = feedback["feedback"]
            suggestions = feedback.get("suggestions", [])
            warning = feedback.get("warning", "")
            msg=" ".join([warning] + suggestions)
            # print('msg:'+msg)
            return {'data':{'message':msg}}
        else:
            user_doc= frappe.new_doc('User')
            user_doc = user_doc.update({
            'first_name': first_name,
            'email': email,
            }).save()
            # print(user_doc.name)
            update_password(user_doc.name,new_password)

            return {'data':{'message':'OK'}}
    else:
        return {'data':{'message':'User is exiest'}}



@frappe.whitelist()
def get_batch_no(serial_and_batch_bundle):
    if serial_and_batch_bundle:
        batch_no_list=frappe.db.get_all('Serial and Batch Entry',filters={'parent':serial_and_batch_bundle},fields=['batch_no'],as_list=True)
        batch_nos=''
        for batch_list in batch_no_list:
            if len(batch_nos)==0:
                batch_nos=batch_list[0]
            else:
                batch_nos=batch_nos+','+batch_list[0]
        return batch_nos
    return ''




@frappe.whitelist()
def get_serial_no(serial_and_batch_bundle):
    if serial_and_batch_bundle:
        batch_no_list=frappe.db.get_all('Serial and Batch Entry',filters={'parent':serial_and_batch_bundle},fields=['serial_no'],as_list=True)
        batch_nos=''
        for batch_list in batch_no_list:
            if len(batch_nos)==0:
                batch_nos=batch_list[0]
            else:
                batch_nos=batch_nos+','+batch_list[0]
        return batch_nos
    return ''


# 自定义 单据编号模板设置 中 字符串
# 如 采购订单   PO-.y_transaction_date.-.####
def get_transaction_date(doc,month_key):
    if month_key in ('Y_transaction_date','y_transaction_date') and hasattr(doc, "transaction_date"):
        return frappe.utils.getdate(doc.transaction_date).strftime(f"%{month_key[0]}%m%d")




import base64
 
# 简易加密
@frappe.whitelist(allow_guest=True)
def encrypt(message):
    return base64.b64encode(message.encode('utf-8'))
 
# 简易解密
@frappe.whitelist()
def decrypt(encrypted_message):
    return base64.b64decode(encrypted_message).decode('utf-8')
 


import re
def remove_p_tags(html_content):
    # 使用正则表达式移除<div>标签及其内容
    pattern = r'<p>(.*?)</p>'
    match = re.search(pattern, html_content, re.DOTALL)
    if match:
        p_content = match.group(1).strip()
        return p_content
    return html_content.strip()








































































































































